<template>
  <div class="app-map">
    <!-- <canvas canvas-id="customMarkerCanvas" style="width: 50px; height: 50px;"></canvas>   -->
    <img :src="i" alt="" v-for="i of imgs">
    <Navbar :isBack="false">
      <view class="head-location" @click="handleChooseLocation">
        <img class="icon1" src="/static/map/location.png" alt="">
        <span>{{locationName}}</span>
        <img class="icon2" src="/static/map/arrow.png" alt="">
      </view>
    </Navbar>
    <map 
      class="map" 
      id="map"
     :style="mapStyle" 
     :scale="14"
     :latitude="location.latitude" 
     :longitude="location.longitude" 
     :markers="markers" 
     @regionchange="handleRegionchange"
     @callouttap="handleMarkertap"
     @markertap="handleMarkertap"	
     ></map>
    <view class="locate-btn" @click="handleChooseLocation"> <img src="/static/map/target.png" alt=""> </view>  
    <view class="search-top" :style="{top:StyleTop}">
      <view class="search">
          <img src="/static/map/search.png" alt="" @click="getListData">
          <input type="text" placeholder="搜索" v-model="form.searchKey" @blur="getListData">
          <img src="/static/map/filter.png" alt="" @click="isFilter=!isFilter">
      </view>
      <view  class="filter" v-if="isFilter">
          <Select label="时间" :title="dateCheck.title + dateCheck.week">
            <view class="filter-list" slot="label">
                  <view class="item"  v-for="(item,i) in dateList" :key="i" :class="{checked:dateCheck.title==item.title}"   @click="handleChangeDate(item)">
                      {{item.title}}
                  </view>
            </view>
          </Select>
          <Select label="类型" :title="tagTitle">
            <view class="filter-list2" @click.stop>
                <view class="list">
                  <view class="item" v-for="(item,i) in typeList" :class="{checked:item.checked}" :key="i" @click="handleChangeType(item)" >
                    {{item.name}}
                  </view>
                </view>
            </view>
          </Select>
      </view>
    </view>
    <Activity :list="list" v-if="list.length" :current="current" @change="handleChangeTab"></Activity>
    <Activity2 :list="list" ></Activity2>
  </div>
</template>
<script>
import Activity from './activity.vue'
import Activity2 from './activity2.vue'
import Select from './select.vue'
let timer=null;
export default {
  components:{Select,Activity,Activity2},
  data() {
    return {
      mapStyle:'',
      current:0,
      imgs:[],
      isFilter:true,
      StyleTop:"",
      locationName:"长沙",
      location:{
        latitude: 28.265297,
			  longitude: 112.875932
      },
      form:{
        tags:[],
        activityTime:"",
        searchKey:"",
        pageNum:1,
        pageSize:30,
        latitude: 28.265297,
			  longitude: 112.875932,
      },
      controls: [{  
        id: 1,  
        iconPath: '/static/map/target.png',
        position: {  
          left: 100,  
          top: 100,  
          width: 50,  
          height: 50  
        },  
        clickable: true  
      }], 
      list:[],
      typeList:[],
      markers: [],
      dateList:[],
      dateCheck:{}
    }
  },
  onLoad(){
    // this.$http('/business/activity/get/map')
    this.dateList=this.getDateList(30)
    this.dateCheck=this.dateList[0]
    this.form.activityTime=this.dateCheck.date
    
    this.getListData()
    this.getTypeList()

  },
  watch:{
    current(val,oldVal){
      this.markers[oldVal].callout.color='#111'
      this.markers[val].callout.color='#16D998'
    }
  },
  computed:{
    tagTitle(){
      if(!this.form.tags.length) return '请选择类型'
      return String(this.form.tags) 
    }
  },
  methods: {
    //筛选日期
    handleChangeDate(item){
      this.dateCheck=item;
      this.form.activityTime=item.date
      this.getListData()
    },
    //筛选类型
    handleChangeType(item){
      item.checked=!item.checked
      this.form.tags=this.typeList.filter(x=>x.checked).map(x=>x.name)
      this.getListData()
    },
    //日期列表
    getDateList(val,label){
        let date = new Date()
        let list=[]
        if(label=='半年' || label=='一年'){
          for(let i=1;i<=val;i++){
              const month=date.getMonth()+1
              list.push(date.getFullYear() +'-'+ month)
              date.setMonth(date.getMonth() -1)
          }
        }else{
          for(let i=1;i<=val;i++){
              let week = date.getDay();  
              let str=''
              if (week == 0) {  
                  str = "星期日";  
              } else if (week == 1) {  
                  str = "星期一";  
              } else if (week == 2) {  
                  str = "星期二";  
              } else if (week == 3) {  
                  str = "星期三";  
              } else if (week == 4) {  
                  str = "星期四";  
              } else if (week == 5) {  
                  str = "星期五";  
              } else if (week == 6) {  
                  str = "星期六";  
              }
              const y=date.getFullYear()
              const m=date.getMonth()+1
              const d=date.getDate()
              const day=d<10?'0'+d:d 
              const month=m<10?'0'+m:m 
              list.push( {date:y+'-'+month+'-'+day, title:month+'-'+day,week:str} )
              date.setDate(date.getDate() +1)
          }
        }
        
        return list
    },
    //创建自定义头像
    createMarker (imgSrc) {
      return Promise((resolve,reject)=>{
        const canvasId = `customMarkerCanvas`; // 生成唯一的canvas ID  
        const canvas = uni.createCanvasContext(canvasId);

        // 设置canvas的大小，这将是标记点图片的大小  
        canvas.width = 25;
        canvas.height = 25;
        uni.getImageInfo({
          src: imgSrc,
          success: (res) => {
            // 在图片上方绘制圆形和留白  
            canvas.beginPath();
            canvas.arc(25, 25, 20, 0, 2 * Math.PI); // 绘制一个较小的圆形，作为留白  
            canvas.setFillStyle('white'); // 留白的颜色  
            canvas.fill();
              // 图片加载完成后，绘制到canvas上  
            canvas.drawImage(res.path, 13, 13, 24, 24); // 假设图片大小为50x50，并且从(0,0)位置开始绘制  

            // 结束绘制  
            canvas.draw(false, () => {
              // 将canvas内容转换为图片，并添加到标记点数组中  
              uni.canvasToTempFilePath({
                canvasId,
                success: (res) => {
                  return resolve(res.tempFilePath)
                }
              });
            });
          }
        });
      })
      
    },
    //选择定位
    handleChooseLocation(){
      uni.authorize({  
        scope: 'scope.userLocation',  
        success:()=> {  
          console.log('用户已授权');  
          uni.chooseLocation({
            success:(res)=> {
              this.location.longitude=res.longitude
              this.location.latitude=res.latitude
              this.form.longitude=res.longitude
              this.form.latitude=res.latitude
              this.locationName=res.name || res.address
              this.getListData()
            },
            fail:(res) => {
              console.log("🚀 ~ handleChooseLocation ~ res:", res)
            }
          })
        },  
        fail() {  
          console.log('用户拒绝授权');  
          // 引导用户手动打开授权页面  
          uni.openSetting({  
            success(res) {  
              console.log(res.authSetting['scope.userLocation']);  
            }  
          });  
        }  
      });
    },
    //类型列表
    getTypeList(){
      this.$http.get("/business/business/topic/list").then(res=>{
        res.retObject.checked=false
        this.typeList=res.retObject
      })
    },
    //数据列表
    getListData(){
      
      this.$http.post("/business/business/activity/get/map",this.form).then(res=>{
        // res.retObject.list.forEach(async x=>{
        //  const url= await this.createMarker(x.imagesList[0])
        //  console.log("🚀 ~ this.$http.post ~ url:", url)
        // })
        this.list=res.retObject.list
        this.markers=res.retObject.list.map((x,i)=>({
          id:x.id,
          latitude: x.latitude,
          longitude: x.longitude,
          width:38,
          height:38,
          iconPath: x.imagesList[0],
          callout:{
            padding:6,
            borderRadius:6,
            bgColor:"#fff",
            color:"#111",
            textAlign: 'center',
            display:"ALWAYS",
            content:x.tags
          }
          
        }))
      })
    }, 
    //地图视图改变
    handleRegionchange(e){
      console.log("🚀 ~ handleRegionchange ~ e:", e)
      if(timer) clearTimeout(timer)
      timer=setTimeout(() => {
        if(e.type=='end'){
          const {latitude,longitude}=e.detail.centerLocation
          this.form.longitude=longitude
          this.form.latitude=latitude
          this.getListData()
        }
      }, 100);
    },
    //点击标点
    handleMarkertap(e){
      const id=e.markerId
      const index=this.list.findIndex(x=>x.id==id)
      this.current=index
    },
    //切换swiper
    handleChangeTab(index){
      this.current=index
    } 
  },

  created() {
   // 获取系统信息，判断当前平台
    uni.getSystemInfo({
      success: (res) => {
        console.log(res)
        const statusBarHeight = res.statusBarHeight || 0;
        const navBarHeight = statusBarHeight + 44;
        this.StyleTop=`${navBarHeight+30}px`
        this.mapStyle=`--mapHeight:${res.windowHeight - navBarHeight}px`
      }
    });
    
  },
  onShareAppMessage(){
    return {
        path: `/pages/map/map`
      };
  }
}
</script>
<style lang="scss" scoped>
.head-location{
  display: flex;
  align-items: center;
  .icon1{
    width: 40rpx;
    height: 40rpx;
    margin-right: 10rpx;
  }
  .icon2{
    width: 23rpx;
    height: 13rpx;
  }
  span{
    font-size: 40rpx;
    font-weight: 500;
    margin-right: 10rpx;
  }
}
.app-map{
  background-color: #f5f5f5;
  .locate-btn{
    position: fixed;
    right: 20rpx;
    bottom: 168rpx;
    img{
      width: 80rpx;
      height: 80rpx;
    }
  }
  .map{
    height: var(--mapHeight);
    width: 100%;
  }
  .search-top{
    position: absolute;
    left: 0;
    width: 100%;
    .search{
      display: flex;
      align-items: center;
      height: 80rpx;
      background: #FFFFFF;
      box-shadow: 0rpx 4rpx 96rpx 0rpx rgba(0,0,0,0.13);
      border-radius: 64rpx 64rpx 64rpx 64rpx;
      // padding: 0 40rpx;
      margin: 0 30rpx;
      img{
        padding: 0 40rpx;
        width: 40rpx;
        height: 40rpx;
      }
      img:first-child{
        padding-right: 0;
      }
      input{
        margin-left: 10rpx;
        font-size: 28rpx;
        color: #101011;
        flex: 1;
      }
    }
    .filter{
      height: 94rpx;
      background: #F8F8F8;
      border-radius: 24rpx 24rpx 24rpx 24rpx;
      margin:0 70rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 30rpx;
      position: relative;
      &>*{
        flex: 1;
      }
      .filter-list{
          position: absolute;
          top: 105%;
          left: 50%;
          transform: translateX(-50%);
          width: 144rpx;
          height: 426rpx;
          background: #FFFFFF;
          border-radius: 20rpx 20rpx 20rpx 20rpx;
          overflow: auto;
          font-size: 26rpx;
          color: #606266;
          .item{
            padding: 30rpx ;
          }
          .item.checked{
            background-color: #16D998;
            color: #101011;
            border-radius: 10rpx;
          }
      }
      .filter-list2{
        width: 100%;
        position: absolute;
        left: 0;
        top: 105%;
        // padding: 0 40rpx;
        .list{
          display: flex;
          align-items: center;
          height: 72rpx;
          background: #FFFFFF;
          overflow: auto;
          white-space: nowrap;
          padding: 0 40rpx;
          border-radius: 92rpx 92rpx 92rpx 92rpx;
          .item{
            padding: 5rpx 10rpx;
          }
          .item.checked{
            background-color: #16D998;
            color: #101011;
            border-radius: 10rpx;
          }
          .item+.item{
            margin-left: 20rpx;
          }
        }
      }
    }
  }
}
</style>